//
//  MHMenuViewController.m
//  MHO
//
//  Created by papo on 2/16/14.
//  Copyright (c) 2014 maihoang. All rights reserved.
//

#import "MHMenuViewController.h"
#import "MHSettingCell.h"
#import "Lib.h"
#import "Contants.h"
#import "Account.h"
#import "UIImageView+WebCache.h"
#import "MHAppDelegate.h"
#import "MHRegisterViewController.h"
#import "MHLoginViewController.h"
#import "MHEventViewController.h"
#import "IPWan.h"
//#import "MHUserInfoViewController.h"
//#import "MHLoginViewController.h"
//#import "MHOptionsViewController.h"

@interface MHMenuViewController ()
{
    NSArray*    cellTitles;
    NSArray*    cellIcons;
}
@property (nonatomic, strong) IBOutlet UITableViewCell* unLoginView;
@property (nonatomic, strong) IBOutlet UITableViewCell* loginView;
@property (weak, nonatomic) IBOutlet UIImageView *userAvatar;
@property (weak, nonatomic) IBOutlet UILabel *userName;
@property (nonatomic, strong) IBOutlet UIView* wifiPassView;
@property (nonatomic, weak) IBOutlet UITextField* wifiPassTf;
@property (assign, nonatomic) BOOL isMHOWifi;
@property (nonatomic, strong) NSString* wifiPass;
@end

@implementation MHMenuViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    [self.tableView registerNib:[UINib nibWithNibName:@"SettingCell" bundle:nil] forCellReuseIdentifier:@"SettingCell"];
    
    cellTitles = @[@"THÔNG TIN TÀI KHOẢN", @"HOME", @"BỘ SƯU TẬP", @"YÊU THÍCH", @"SỰ KIỆN", @"TUỲ CHỌN"];
    cellIcons = @[@"icon_information.png", @"icon_home.png", @"icon_bo_suu_tap.png", @"icon_favorite.png", @"icon_su_kien.png", @"icon_setting.png"];
    
    [self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForItem:2 inSection:0] animated:NO scrollPosition:UITableViewScrollPositionNone];
    
    if (self.wifiPass) {
        self.wifiPassTf.text = self.wifiPass;
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSAssert(cellTitles.count == cellIcons.count, @"Error! cellIcons.count != cellTitles.count!");
    // Return the number of rows in the section.
    if (self.isMHOWifi) {
        return cellIcons.count + 2;
    }
    return cellIcons.count + 1;
}

//- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
//    
//}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if  (section == 0 && [Lib isIos7]) {
//        return 20;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"SettingCell";
    if (indexPath.row == 0) {
        CellIdentifier = @"Cell";
        UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        
        if (!cell) {
//            cell = [[UITableViewCell alloc] init];
            
            if ([Lib isUserLogin]) {
                cell = self.loginView;
            }
            else {
                // create login button
                cell = self.unLoginView;
            }
            [cell setBackgroundColor:[UIColor clearColor]];
            [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        }
        // check login
        if ([Lib isUserLogin]) {
            self.userName.text = [Lib stringForKey:kAccountPublicName];
            NSString* av = strCheckNull([Lib stringForKey:@"Avatar"]);
            if (av.length > 0) {
                [self.userAvatar setImageWithURL:[NSURL URLWithString:av] placeholderImage:[UIImage imageNamed:@"avatar.png"]];
            }
        }
        else {
            
        }
        
        return cell;
    }
    else if (indexPath.row == cellIcons.count + 1) {
        UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:@"CellIdentifier"];
        if (!cell) {
            cell = [[UITableViewCell alloc] init];
            [cell.contentView addSubview:self.wifiPassView];
        }
        return cell;
    }

    MHSettingCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [MHSettingCell cellFromNib];
//        if ((indexPath.row % 2) == 0)
        {
            [cell setBackgroundColor:self.view.backgroundColor];
        }
//        else {
//            [cell setBackgroundColor:[UIColor blackColor]];
//        }
        UIImageView* bgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"bg_focus_infomation.png"]];
        [cell setSelectedBackgroundView:bgView];
    }

    // Configure the cell...
    
    {
        cell.titile.text = cellTitles[indexPath.row - 1];
        cell.icon.image = [UIImage imageNamed:cellIcons[indexPath.row - 1]];
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        return 100;
    }
    else if (indexPath.row == cellIcons.count + 1) {
        return self.wifiPassView.frame.size.height;
    }
    return 50;
}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/


#pragma mark - Table view delegate

// In a xib-based application, navigation from a table can be handled in -tableView:didSelectRowAtIndexPath:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0) {
        switch (indexPath.row - 1) {
            case 0: // user info
                if ([Lib isUserLogin]) {
                    [[MHAppDelegate sharedApp].viewController showUserVc];
                }
                else {
                    [[MHAppDelegate sharedApp].viewController showLoginVc];
                }
                break;
            case 1: // home
                [[MHAppDelegate sharedApp].viewController showHomeVc];
                break;
            case 2: // bo suu tap
            {
                if ([Lib isUserLogin]) {
                    [[MHAppDelegate sharedApp].viewController showCollectionVc];
                }
                else {
                    [[MHAppDelegate sharedApp].viewController showLoginVc];
                }
            }
                break;
            case 3:{
                if ([Lib isUserLogin]) {
                    [[MHAppDelegate sharedApp].viewController showAppCollectListVc];
                }
                else {
                    [[MHAppDelegate sharedApp].viewController showLoginVc];
                }
            }
                break;
            case 4: // su kien
                [[MHAppDelegate sharedApp].viewController showEventVc];
                break;
            case 5: // tuy chon
                [[MHAppDelegate sharedApp].viewController showOptionVc];
                break;
            default:
                break;
        }
    }
}


- (IBAction)loginButtonPressed: (id)sender {
//    [self showLoginAlert];
    [[MHAppDelegate sharedApp].viewController showLoginVc];
}

- (IBAction)registerButtonPressed: (id)sender {
    [[MHAppDelegate sharedApp].viewController showRegisVc];
}

- (void)showLoginAlert {
    UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Đăng nhập" message:@"" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:@"Huỷ", nil];
    alert.alertViewStyle = UIAlertViewStyleLoginAndPasswordInput;
    [alert textFieldAtIndex:0].keyboardType = UIKeyboardTypeEmailAddress;
    alert.tag = 123;
    [alert show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (alertView.tag == 123) {
        if (buttonIndex == 0) {
            // ok
//            NSString* email = [[alertView textFieldAtIndex:0] text];
//            NSString* password = [alertView textFieldAtIndex:1].text;
//            
//            NSDictionary* dict = @{kAccountEmail:email, kAccountPassword: password };
//            [Lib showLoadingViewOnView:self.view];
//            
//            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//                ServiceResult* result = [Account loginWithInfo:dict];
//                
//                dispatch_async(dispatch_get_main_queue(), ^{
//                    [Lib removeLoadingViewOnView:self.view];
//                    [self updateUserInfo];
//                    if (result.success) {
//                        [self showMessage:@"Đăng nhập thành công!" title:@""];
//                    }
//                    else {
//                        [self showMessage:result.message title:@""];
//                    }
//                });
//            });
        }
        else {
            // do nothing
        }
    }
}

- (void)showMessage:(NSString*)message title:(NSString*)title {
    UIAlertView* alert = [[UIAlertView alloc] initWithTitle:title message:message delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
    [alert show];
}


- (void)updateUserInfo {
    if (![Lib isUserLogin]) {
        [self.tableView reloadData];
        return;
    }
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        Account* result = [Account getCurrentUserInfo];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [Lib removeLoadingView];
            [self.tableView reloadData];
            if (result) {
                
            }
            else {
//                [self showMessage:@"Co loi xay ra!" title:@""];
            }
        });
    });
}

- (IBAction)logoutButtonPressed:(id)sender {
    [Lib setUserLogin:NO];
    [self.tableView reloadData];
}

- (void)updateWifiPass:(BOOL)isMHOWifi pass:(NSString *)password {
    self.isMHOWifi = isMHOWifi;
    self.wifiPass = password;
    self.wifiPassTf.text = password;
    [self.tableView reloadData];
}

- (IBAction)copyWifiPass:(id)sender {
    if (self.wifiPass) {
        [[UIPasteboard generalPasteboard] setString:self.wifiPass];
    }
    [Lib showMessage:@"Đã copy password vào clipboard!" title:@""];
}
@end
